import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:just_interview/markdown.dart';
import 'package:just_interview/storage.dart';

class SubTypePage extends StatefulWidget {
  String keyword;
  SubTypePage({
    super.key,
    required this.keyword,
  });

  @override
  State<SubTypePage> createState() => _SubTypePageState();
}

class _SubTypePageState extends State<SubTypePage> {
  List questions = [];

  getStorageQuestions() async {
    questions = jsonDecode(
      await getStorage(key: widget.keyword, initData: "[]"),
    );
    setState(() {});
  }

  Map content = {};

  getAnswer(String topic_id) async {
    var dio = Dio();
    var response = await dio.request(
      'http://49.232.224.53:8000/v5/get_topic_detail_content_app_uuid?topic_id=$topic_id',
      options: Options(
        method: 'GET',
      ),
    );

    if (response.statusCode == 200) {
      content = response.data["data"];
      setState(() {});
    } else {}
  }

  getQuestions() async {
    var dio = Dio();
    var keyword = widget.keyword.replaceAll("+", "%2b");
    var response = await dio.request(
      'http://49.232.224.53:8000/v5/search_topic_23_app_uuid?column_id=23&limit=200&search_content=${keyword}',
      options: Options(
        method: 'GET',
      ),
      data: {},
    );

    if (response.statusCode == 200) {
      setState(() {
        questions = response.data["data"]["data"];
        setStorage(key: widget.keyword, value: jsonEncode(questions));
      });
    } else {}
  }

  @override
  void initState() {
    getStorageQuestions();
    getQuestions();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xfffdf7fe),
        // title: Text(
        //   widget.keyword,
        //   style: TextStyle(
        //     fontSize: 16,
        //     fontWeight: FontWeight.normal,
        //   ),
        // ),
      ),
      body: Row(
        children: [
          Container(
            width: 400,
            child: ListView(
              children: [
                if (questions.isEmpty)
                  Center(
                    child: Container(
                      margin: EdgeInsets.only(top: 50),
                      child: CircularProgressIndicator(),
                    ),
                  ),
                ...List.generate(questions.length, (idx) {
                  var ele = questions[idx];
                  return ListTile(
                    leading: CircleAvatar(child: Text((idx + 1).toString())),
                    onTap: () {
                      getAnswer(ele["topic_id"]);
                    },
                    title: Text(ele["topic_title"].toString().split("】")[
                        ele["topic_title"].toString().split("】").length - 1]),
                  );
                }),
              ],
            ),
          ),
          Expanded(
            child: (content["topic_title"] == null)
                ? Center(
                    child: Container(
                      padding: EdgeInsets.only(bottom: 100),
                      child: questions.isEmpty
                          ? Container()
                          : Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.explore,
                                  size: 100,
                                  color: Colors.grey[300],
                                ),
                                Container(height: 20),
                                Text(
                                  "请选中一个题目",
                                  style: TextStyle(
                                    color: Colors.grey[500],
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal,
                                  ),
                                ),
                              ],
                            ),
                    ),
                  )
                : ListView(
                    children: [
                      if (content["topic_title"] != null)
                        Card(
                          child: Container(
                            child: Text(
                              content["topic_title"].toString().split("】")[
                                  content["topic_title"]
                                          .toString()
                                          .split("】")
                                          .length -
                                      1],
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            padding: EdgeInsets.symmetric(
                              horizontal: 25,
                              vertical: 20,
                            ),
                          ),
                        ),
                      if (content["topic_title"] != null)
                        Card(
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 25,
                              vertical: 20,
                            ),
                            child: MarkdownBody(
                              text: content["topic_content"].toString(),
                              tap: () {},
                              isLight: true,
                            ),
                          ),
                        ),
                    ],
                  ),
          ),
        ],
      ),
    );
  }
}
